package base

import (
	"sen-golang-study/go_game_study/hero_story_go_server/common/main_thread"
	"sync/atomic"
)

type AsyncBizResult struct {
	returnedObj  interface{}
	completeFunc func()

	hasReturnedObj                   int32
	hasCompleteFunc                  int32
	completeFuncHasAlreadyBeenCalled int32
}

func (result *AsyncBizResult) GetReturnedObj() interface{} {
	return result.returnedObj
}

func (result *AsyncBizResult) SetReturnObj(val interface{}) {
	if atomic.CompareAndSwapInt32(&result.hasReturnedObj, 0, 1) {
		result.returnedObj = val
		result.DoComplete()
	}
}

func (result *AsyncBizResult) OnComplete(completeFunc func()) {
	if atomic.CompareAndSwapInt32(&result.hasCompleteFunc, 0, 1) {
		result.completeFunc = completeFunc

		if result.hasReturnedObj == 1 {
			result.DoComplete()
		}
	}
}

func (result *AsyncBizResult) DoComplete() {
	if result.completeFunc != nil &&
		atomic.CompareAndSwapInt32(&result.completeFuncHasAlreadyBeenCalled, 0, 1) {
		main_thread.PushTask(result.completeFunc)
	}
}
